var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//导入数据库*****************************************
require('./utils/db')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var typesRouter = require('./routes/types');
var sellersRouter = require('./routes/sellers');
var uploadRouter = require('./routes/upload');
var typesRouter = require('./routes/types');
var claimsRouter = require("./routes/claims")
var ordersRouter = require('./routes/orders')
var insurancesRouter = require('./routes/insurances')
// var loginRouter = require('./routes/login')



var app = express();
/* 
  跨域的中间件处理函数
*/
const allowCross=(req,res,next)=>{
  res.setHeader('Access-Control-Allow-Origin','*') //允许的域，白名单设置

  res.setHeader('Access-Control-Allow-Headers','X-Requested-With,Origin,Content-Type,Accept,Authorization')//除了9请求头之外的请求头
  res.setHeader('Access-Control-Allow-Methods','PUT,DELETE,OPTIONS') //允许的请求方式
  next()
}

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//设置跨域的自定义中间件
app.use(allowCross)

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/sellers', sellersRouter);
app.use('/upload', uploadRouter);
app.use('/types', typesRouter);
app.use('/insurances', insurancesRouter);
// app.use('/admins',loginRouter)
app.use('/claims',claimsRouter)
app.use('/orders', ordersRouter)



// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen('3002', () => {
  console.log('服务器已启动');
})

module.exports = app;
